<script lang="ts" setup>
import type {
  AssetDetailResponse,
  AssetPageRequest,
  AssetPageResponse,
  PageRequest,
  SysClientResponse,
} from '#/api/kingtown/types';

import {
  createVNode,
  h,
  nextTick,
  onBeforeMount,
  onMounted,
  reactive,
  ref,
  unref,
} from 'vue';

import {
  BarsOutlined,
  DeleteOutlined,
  DownOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  SaveOutlined,
  StopOutlined,
  UpOutlined,
} from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';

import AssetBasicDetail from '#/views/asset/component/AssetBasicDetail.vue';

import {
  listClientsApi,
  listColumnsApi,
  pageAssetApi,
  updateAssetApi,
} from '../../api/kingtown';

onBeforeMount(async () => {
  await fetchListColumns();
});

onMounted(() => {
  console.warn('onMounted');
  fetchData();
  fetchClients();
});

const showExtend = ref<Boolean>(false);
const editableData: Record<string, AssetPageResponse> = reactive({});
const openDetail = ref<Boolean>(false);
const targetAsset = ref<AssetDetailResponse>();
const clients = ref<SysClientResponse[]>([]);
const refreshKey = ref<number>(0);

const params = ref<AssetPageRequest>({
  clientId: '',
  assetCode: '',
  assetName: '',
  assetFloor: '',
  assetAddress: '',
  tagStatus: '',
  inventoryStatus: '',
});
const pageRequest = ref<PageRequest>({
  current: 0,
  size: 10,
  query: unref(params),
});
const dataSource = ref<AssetPageResponse[]>([]);
const columns = ref();

const fetchListColumns = async () => {
  const res = await listColumnsApi();
  res.push({
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 180,
    align: 'center',
  });
  console.warn('接口返回数据', res);
  columns.value = res;
};

const fetchData = async () => {
  const result = await pageAssetApi(pageRequest.value);
  dataSource.value = result.records;
  console.log('pageAssetApi', result);
};

const reload = async () => {
  pageRequest.value.current = 1;
  await fetchData();
};

const changeShowExtend = () => {
  showExtend.value = !showExtend.value;
};

const handleDetail = async (record: any) => {
  console.warn(record);
  targetAsset.value = record;
  await nextTick();
  refreshKey.value = Math.random();
  console.log(
    '此处的targetAsset是',
    targetAsset.value,
    'refreshKey是',
    refreshKey.value,
  );
  openDetail.value = true;
};
const handleEdit = (record: any) => {
  dataSource.value.forEach((item) => {
    console.info('看看item, item id, key', item, item.id, record.id);
    if (String(record.id) === String(item.id)) {
      editableData[String(record.id)] = deepClone(item);
    } else {
      console.warn('不应该不相同');
    }
  });
};
const handleDelete = (record: any) => {
  console.warn(record);
  Modal.confirm({
    title: '删除资产',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定删除该资产及其相关数据？',
    onOk() {
      return new Promise((resolve, reject) => {
        setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
      }).catch(() => console.log('Oops errors!'));
    },
    onCancel() {},
  });
};
const handleSave = (key: string) => {
  const item = dataSource.value.find((item) => key === String(item.id));
  if (item) {
    Object.assign(item, editableData[key]);
    updateAssetApi(item).then((res) => {
      console.log('updateAssetApi result', res);
      delete editableData[key];
      message.success('修改成功');
    });
  } else {
    console.warn(`未找到 id 为 ${key} 的项`);
  }
};
const handleCancel = (key: string) => {
  delete editableData[key];
};
const closeLifecycle = () => {
  openDetail.value = false;
};
const deepClone = (original: any) => {
  return JSON.parse(JSON.stringify(original));
};
const fetchClients = async () => {
  clients.value = await listClientsApi();
  if (clients.value.length > 0) {
    params.value.clientId = clients.value[0]?.id || '';
  }
};
</script>
<template>
  <div class="page-wrap">
    <div class="action-wrap">
      <a-space>
        <a-button type="primary">新增</a-button>
        <a-button type="primary">导入</a-button>
        <a-button type="primary">导出</a-button>
        <a-button>导入模板下载</a-button>
      </a-space>
      <div class="search-wrap">
        <div style="display: flex; flex: 1; flex-direction: column">
          <a-space>
            <span>所属客户</span>
            <a-select v-model:value="params.clientId" style="width: 120px">
              <a-select-option v-for="client in clients" :value="client.id">
                {{ client.clientName }}
              </a-select-option>
            </a-select>
            <span>资产编码</span>
            <a-input style="width: 120px" v-model:value="params.assetCode" />
            <span>资产名称</span>
            <a-input style="width: 120px" v-model:value="params.assetName" />
            <span>所在楼层</span>
            <a-input style="width: 120px" v-model:value="params.assetFloor" />
            <span>所在位置</span>
            <a-input style="width: 120px" v-model:value="params.assetAddress" />
            <a-button type="primary" @click="reload">搜索</a-button>
            <a-button
              type="link"
              size="small"
              :icon="h(showExtend ? UpOutlined : DownOutlined)"
              @click="changeShowExtend"
            >
              {{ showExtend ? '收起' : '展开' }}
            </a-button>
          </a-space>

          <div
            style="margin-top: 8px"
            :class="{ 'search-extend': !showExtend }"
          >
            <a-space>
              <span>标签状态</span>
              <a-select v-model:value="params.tagStatus" style="width: 120px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="正常">无异常</a-select-option>
                <a-select-option value="标签卷边">标签卷边</a-select-option>
                <a-select-option value="无标签">无标签</a-select-option>
              </a-select>
              <span>盘点状态</span>
              <a-select
                v-model:value="params.inventoryStatus"
                style="width: 120px"
              >
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="0">未盘</a-select-option>
                <a-select-option value="1">新增</a-select-option>
                <a-select-option value="2">已盘</a-select-option>
                <a-select-option value="3">重复已盘</a-select-option>
              </a-select>
            </a-space>
          </div>
        </div>
        <a-space />
      </div>
    </div>

    <div class="content-wrap">
      <a-table :data-source="dataSource" :columns="columns">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column?.key === 'inventoryStatus'">
            <a-tag v-if="record.inventoryStatus === '已盘'" color="blue">
              在库
            </a-tag>
            <a-tag v-else-if="record.inventoryStatus === '未盘'" color="red">
              未盘
            </a-tag>
            <a-tag v-else color="orange">新增</a-tag>
          </template>

          <template
            v-if="
              [
                'assetName',
                'assetFloor',
                'assetAddress',
                'color',
                'abnormalReason',
                'remark',
              ].includes(column?.dataIndex)
            "
          >
            <div>
              <a-input
                v-if="editableData[record.id] && column?.dataIndex"
                v-model:value="
                  editableData[record.id]![
                    column?.dataIndex as keyof AssetPageResponse
                  ]
                "
                style="margin: -5px 0"
              />
              <template v-else-if="column?.key === 'abnormalReason'">
                <a-tag v-if="record.abnormalReason === '标签卷边'" color="red">
                  标签卷边
                </a-tag>
                <a-tag
                  v-else-if="record.abnormalReason === '无标签'"
                  color="red"
                >
                  无标签
                </a-tag>
                <a-tag v-else color="blue">无异常</a-tag>
              </template>
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template v-if="column?.key === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[String(record.id)]">
                <a-button
                  class="button-interval"
                  type="link"
                  size="small"
                  :icon="h(SaveOutlined)"
                  @click="handleSave(String(record.id))"
                >
                  保存
                </a-button>
                <a-button
                  class="button-interval"
                  type="link"
                  size="small"
                  :icon="h(StopOutlined)"
                  @click="handleCancel(String(record.id))"
                >
                  取消
                </a-button>
              </span>
              <span v-else>
                <a-button
                  class="button-interval"
                  type="link"
                  size="small"
                  :icon="h(BarsOutlined)"
                  @click="handleDetail(record)"
                >
                  查看
                </a-button>
                <a-button
                  class="button-interval"
                  type="link"
                  size="small"
                  :icon="h(EditOutlined)"
                  @click="handleEdit(record)"
                >
                  修改
                </a-button>
                <a-button
                  class="button-interval"
                  type="link"
                  size="small"
                  :icon="h(DeleteOutlined)"
                  @click="handleDelete(record)"
                >
                  删除
                </a-button>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <AssetBasicDetail
      :open="openDetail"
      @close="closeLifecycle"
      :asset="targetAsset"
      :refresh-key="refreshKey"
    />
  </div>
</template>
<style scoped>
.search-extend {
  display: none;
}
</style>
